﻿/*******************************************************************************
 * Copyright © 2016 DJY 版权所有
 * Author: DJY
 * Description: 后台管理系统
 * Website：http://www.djyweb.cn
*********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Text;
using DynamicExpresso;
using DJY.Code.Helper;

namespace DJY.Code
{
    /// <summary>
    /// 常用公共类
    /// </summary>
    public static class Common
    {
        #region Stopwatch计时器
        /// <summary>
        /// 计时器开始
        /// </summary>
        /// <returns></returns>
        public static Stopwatch TimerStart()
        {
            Stopwatch watch = new Stopwatch();
            watch.Reset();
            watch.Start();
            return watch;
        }
        /// <summary>
        /// 计时器结束
        /// </summary>
        /// <param name="watch"></param>
        /// <returns></returns>
        public static string TimerEnd(Stopwatch watch)
        {
            watch.Stop();
            double costtime = watch.ElapsedMilliseconds;
            return costtime.ToString();
        }
        #endregion

        #region 删除数组中的重复项
        /// <summary>
        /// 删除数组中的重复项
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static string[] RemoveDup(string[] values)
        {
            List<string> list = new List<string>();
            for (int i = 0; i < values.Length; i++)//遍历数组成员
            {
                if (!list.Contains(values[i]))
                {
                    list.Add(values[i]);
                };
            }
            return list.ToArray();
        }
        #endregion

        #region 自动生成编号
        /// <summary>
        /// 表示全局唯一标识符 (GUID)。
        /// </summary>
        /// <returns></returns>
        public static string GuId()
        {
            return Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            System.Random random = new System.Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }
        #endregion

        #region 生成0-9随机数
        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="codeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int codeNum)
        {
            StringBuilder sb = new StringBuilder(codeNum);
            System.Random rand = new System.Random();
            for (int i = 1; i < codeNum + 1; i++)
            {
                int t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();

        }
        #endregion

        #region 删除最后一个字符之后的字符
        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }
        /// <summary>
        /// 删除最后结尾的长度
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string DelLastLength(string str, int Length)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            str = str.Substring(0, str.Length - Length);
            return str;
        }
        #endregion

        /// <summary>
        /// 格式化金额
        /// </summary>
        /// <param name="amount">金额</param>
        /// <returns></returns>
        public static string FormatAmount(decimal amount)
        {
            if (amount < 1000)
            {
                return amount.ToString();
            }
            else if(amount < 10000000)
            {
                return string.Format("{0:f4}万元", amount / 10000);
            }
            else
            {
                return string.Format("{0:f4}亿元", amount / 100000000);
            }

        }

        /// <summary>
        /// 显示具体的错误信息
        /// </summary>
        /// <param name="ex">异常</param>
        /// <returns></returns>
        public static string ShowException(Exception ex)
        {
            while(ex.InnerException != null)
            {
                ex = ex.InnerException;
            }

            return ex.Message;
        }

        #region 字符串操作
        /// <summary>
        /// 忽略大小写判断相等
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool EqualsIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return true;

            if (str1 == null || str2 == null)
            {
                return false;
            }

            return string.Equals(str1.ToString(), str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// str1 以 str2开头
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool StartsWithIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return true;

            if (str1 == null || str2 == null)
            {
                return false;
            }

            return str1.ToString().StartsWith(str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// str1 以 str2 结尾
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool EndsWithIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return true;

            if (str1 == null || str2 == null)
            {
                return false;
            }

            return str1.ToString().EndsWith(str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 忽略大小写 比较
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static int CompareIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return 0;

            if (str1 == null || str2 == null)
            {
                return 0;
            }

            return string.Compare(str1.ToString(), str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 索引位置
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static int IndexOfIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return -1;

            if (str1 == null || str2 == null)
            {
                return -1;
            }

            return str1.ToString().IndexOf(str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 匹配最后一个索引位置
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static int LastIndexOfIgnorecase(object str1, object str2)
        {
            if (str1 == null && str2 == null)
                return -1;

            if (str1 == null || str2 == null)
            {
                return -1;
            }

            return str1.ToString().LastIndexOf(str2.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 字符串判断相等
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool IsEqual(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1) && string.IsNullOrEmpty(str2))
                return true;

            return string.Equals(str1, str2);
        }
        #endregion

        /// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="obj">参数</param>
        /// <param name="paramName">参数名</param>
        /// <returns></returns>
        public static Interpreter NewInterpreter(Action<Interpreter> addRef = null)
        {
            Interpreter expr = new Interpreter(InterpreterOptions.Default)
                .EnableReflection()
                .Reference(typeof(ExpandoObject))
                .Reference(typeof(DynamicExpressoHelper))
                .SetFunction("equalsIgnore", (Func<object, object, bool>)EqualsIgnorecase)
                .SetFunction("startsIgnore", (Func<object, object, bool>)StartsWithIgnorecase)
                .SetFunction("endsIgnore", (Func<object, object, bool>)EndsWithIgnorecase)
                .SetFunction("compareIgnore", (Func<object, object, int>)CompareIgnorecase)
                .SetFunction("indexOfIgnore", (Func<object, object, int>)IndexOfIgnorecase)
                .SetFunction("lastIndexOfIgnore", (Func<object, object, int>)LastIndexOfIgnorecase);

            if(addRef != null)
            {
                addRef.Invoke(expr);
            }
            return expr;
        }

        /// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="obj">参数</param>
        /// <param name="paramName">参数名</param>
        /// <returns></returns>
        public static T Eval<T>(this string str, object obj = null, string paramName = "obj")
        {
            Interpreter expr = new Interpreter(InterpreterOptions.Default)
                .EnableReflection()
                .Reference(typeof(ExpandoObject))
                .Reference(typeof(DynamicExpressoHelper))
                .SetFunction("equalsIgnore", (Func<object, object, bool>)EqualsIgnorecase)
                .SetFunction("startsIgnore", (Func<object, object, bool>)StartsWithIgnorecase)
                .SetFunction("endsIgnore", (Func<object, object, bool>)EndsWithIgnorecase)
                .SetFunction("compareIgnore", (Func<object, object, int>)CompareIgnorecase)
                .SetFunction("indexOfIgnore", (Func<object, object, int>)IndexOfIgnorecase)
                .SetFunction("lastIndexOfIgnore", (Func<object, object, int>)LastIndexOfIgnorecase);
            if (obj != null)
            {
                paramName = paramName ?? "obj";
                expr.SetVariable(paramName, obj);
            }
            return expr.Eval<T>(str);
        }
    }
}
